package com.mybatis.crudservice.tools;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ 描 述 :
 * @ 作 者 : 一念〃
 * @ 时 间 : 15:46 2019/6/8
 * @ 备 注 :
 */
public class JsonUtils {

    private final static ObjectMapper mapper = new ObjectMapper();

    public static HashMap<String,Object> JsonStrToMap(String str) throws IOException{
        HashMap<String,Object> result = new HashMap<>();
        if(str != null && !"".equals(str)) {
            result = (HashMap) mapper.readValue(str, Map.class);
        }
        return result;
    }

    public static List<Object> JsonStrToList(String str) throws IOException{
        List<Object> result = new ArrayList<>();
        if(str != null && !"".equals(str)) {
            result = (List) mapper.readValue(str, List.class);
        }
        return result;
    }

    public static String MapToJsonStr(Map<String,Object> map) throws IOException{
        String result = mapper.writeValueAsString(map);
        return result;
    }

    /**
     * 字符串转List
     * @param str
     * @return
     * @throws IOException
     */
    public static List<Map<String,Object>> strToList(String str) throws IOException{
        List<Map<String,Object>> result = new ArrayList<>();
        if(str != null && !"".equals(str)) {
            result = (List) mapper.readValue(str, List.class);
        }
        return result;
    }

    /**
     * 字符串转Map
     * @param str
     * @return
     * @throws IOException
     */
    public static HashMap<String,Object> strToMap(String str) throws IOException{
        HashMap<String,Object> result = new HashMap<>();
        if(str != null && !"".equals(str)) {
            result = (HashMap) mapper.readValue(str, Map.class);
        }
        return result;
    }

    /**
     * json 转JavaBean
     * @param jsonString
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz) throws IOException {
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return mapper.readValue(jsonString, clazz);
    }

}
